/****************************************************************************
*                                                                           *
* Copyright (c) RSC. All rights reserved(2010).								*
* Developer: Marius Ionescu    						                        *
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web.Security;
using System.Web.UI.WebControls;
using NS_Controls;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.UI;
using AjaxControlToolkit;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Threading;
using System.Globalization;
using System.IO;
using System.Text;

public partial class ExportCM : SessionPageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }
    }

    protected void LoadData()
    {
        try
        {
            txtDataStart.Text = System.DateTime.Now.Date.ToString("dd/MM/yyyy");
            txtDataEnd.Text = System.DateTime.Now.Date.ToString("dd/MM/yyyy");
        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        output.Text = "";
        DateTime startAll = DateTime.Now;

        DateTime selectedStartDate = Tools.getDateFormat_CultureInfo(txtDataStart.Text);
        DateTime selectedEndDate = Tools.getDateFormat_CultureInfo(txtDataEnd.Text);

        object[] dates = new object[] { selectedStartDate, selectedEndDate };
        DataSet dsSelectExportData_CM = Hipocrate.DB.DBConnection.GetData("SelectExportData_CM", new string[] { "startDate", "endDate" }, dates);
        DataView dv = dsSelectExportData_CM.Tables[0].DefaultView;

        object sqlReturnValue = null;
        string pathFile = Server.MapPath("~/Tools/TempCM/template.dbf");
        string sqlQuery = "";

        if (!System.IO.File.Exists(pathFile))
            throw new ApplicationException("Cannot find file: " + pathFile);

        OleDbConnection dbConn = new OleDbConnection(@"Provider=vfpoledb.1;Data Source=" + pathFile + ";Collating Sequence=general");

        try
        {
            dbConn.Open();

            if (dv.Count > 0)
            {
                for (int i = 0; i < dv.Count; i++)
                {
                    sqlQuery = @"INSERT INTO Template 
				    (tip_rectif, seria, numar, bis, d_seria, d_numar, luna, an_ccm, urgenta, infect, cod_indemn, 
		            am_in_ex, data_aco, data_amb_i, data_amb_s, data_ext_i, data_ext_s, cod_diagn1, cod_diagn2, 
                    cnp_a, cod_parafa, initial, me_nr, me_data, me_parafa,paraf_m_se, muncii_par, cas, nume_c, cui, conventie, cas_medic, ln, an, tipd ) 
                    VALUES('" + dv[i]["TIP_RECTIF"].ToString().Trim() + @"','"
                            + dv[i]["SERIA"].ToString().Trim() + @"','"
                            + dv[i]["NUMAR"].ToString().Trim() + @"',"
                            + Tools.GetSQLValueNULL(dv[i]["BIS"].ToString().Trim(), false) + @",'"
                            + dv[i]["D_SERIA"].ToString().Trim() + @"','"
                            + dv[i]["D_NUMAR"].ToString().Trim() + @"',"
                            + dv[i]["LUNA"].ToString().Trim() + @","
                            + dv[i]["AN_CCM"].ToString().Trim() + @","
                            + dv[i]["URGENT"].ToString().Trim() + @","
                            + Tools.GetSQLValueNULL(dv[i]["INFECT"].ToString().Trim(), false) + @",'"
                            + dv[i]["COD_INDEMN"].ToString().Trim() + @"','"
                            + dv[i]["AM_IN_EX"].ToString().Trim() + @"',"
                            + Tools.GetDateFormatDBF(Tools.getDBFFormat_ISO(dv[i]["DATA_ACO"])) + @","
                            + Tools.GetDateFormatDBF(Tools.getDBFFormat_ISO(dv[i]["DATA_AMB_I"])) + @","
                            + Tools.GetDateFormatDBF(Tools.getDBFFormat_ISO(dv[i]["DATA_AMB_S"])) + @","
                            + Tools.GetDateFormatDBF(Tools.getDBFFormat_ISO(dv[i]["DATA_EXT_I"])) + @","
                            + Tools.GetDateFormatDBF(Tools.getDBFFormat_ISO(dv[i]["DATA_EXT_S"])) + @",'"
                            + dv[i]["COD_DIAGN1"].ToString().Trim() + @"','"
                            + dv[i]["COD_DIAGN2"].ToString().Trim() + @"','"
                            + dv[i]["CNP_A"].ToString().Trim() + @"','"
                            + dv[i]["COD_PARAFA"].ToString().Trim() + @"',"
                            + dv[i]["INITIAL"].ToString().Trim() + @",'"
                            + dv[i]["ME_NR"].ToString().Trim() + @"',"
                            + Tools.GetDateFormatDBF(Tools.getDBFFormat_ISO(dv[i]["ME_DATA"])) + @",'"
                            + dv[i]["ME_PARAFA"].ToString().Trim() + @"','"
                            + dv[i]["PARAF_M_SE"].ToString().Trim() + @"','"
                            + dv[i]["MUNCII_PAR"].ToString().Trim() + @"','"
                            + dv[i]["CAS"].ToString().Trim() + @"','"
                            + dv[i]["NUME_C"].ToString().Trim() + @"','"
                            + dv[i]["CUI"].ToString().Trim() + @"','"
                            + dv[i]["CONVENTIE"].ToString().Trim() + @"','"
                            + dv[i]["CAS_MEDIC"].ToString().Trim() + @"',"
                            + dv[i]["LN"].ToString().Trim() + @","
                            + dv[i]["AN"].ToString().Trim() + @","
                            + dv[i]["TIPD"].ToString() + @")";

                    sqlReturnValue = Hipocrate.DB.DBConnection.ExecuteNonQuery_DBF(sqlQuery, pathFile, dbConn);
                }
            }

            output.Text = "<strong>Au fost exportate " + dv.Count.ToString() + " concedii medicale.</strong>";
        }
        catch (OleDbException ex)
        {
            output.Text = ex.Message;
        }
        finally
        {
            dbConn.Close();

            string js = "hideModal()";
            ScriptManager.RegisterStartupScript(this, typeof(ExportCM), "hideModal", js, true);
        }
    }

    protected void btnClear_Click(object sender, EventArgs e)
    {
        output.Text = "";
        try
        {
            string path = Server.MapPath("~/Tools/TempCM/template.dbf");
            string pathIni = Server.MapPath("~/Tools/TempCM/template_ini.dbf");

            if (System.IO.File.Exists(pathIni))
            {
                try
                {
                    System.IO.File.Copy(pathIni, path, true);
                    output.Text = "Fisierul a fost suprascris direct.";
                    return;
                }
                catch (System.IO.IOException) { }
            }

            this.SetMessage(Resources.DatabaseStrings.DocumentSaved2, false);
        }
        catch (Exception ex)
        {
            output.Text = ex.ToString();
        }
    }

    protected void btnDownload_Click(object sender, EventArgs e)
    {
        string xName = DateTime.Today.ToShortDateString().Replace(".","_") + "__" + DateTime.Now.ToShortTimeString().Replace(":","_") + ".dbf";
        string filepath = Server.MapPath("~/Tools/TempCM/" + xName);
        string pathIni = Server.MapPath("~/Tools/TempCM/template.dbf");

        try
        {
            if (System.IO.File.Exists(pathIni))
            {
                try
                {
                    System.IO.File.Copy(pathIni, filepath, true);
                    output.Text = "Fisierul a fost suprascris direct.";
                }
                catch (System.IO.IOException) { }
            }
        }
        catch (Exception ex)
        {
            output.Text = ex.ToString();
        }

        Response.Redirect("~/Tools/ExportDBF.ashx?fileName=" + xName);
    }

}
